/**
 * AppPushUtils.java
 * Created at 2018-1-29
 * Created by zhanghailin
 * Copyright (C) 2018 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.message;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.broadtext.common.utils.StringUtils;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.gexin.rp.sdk.template.style.Style0;

/**
 * <p>ClassName: AppPushUtils</p>
 * <p>Description: 个推消息推送接口</p>
 * <p>Author: zhanghailin</p>
 * <p>Date: 2018-1-29</p>
 */
public class AppPushUtils {
    
    //提醒模板
    public static String NOTIFICATION_TEMPLATE = "1";
    
    //透穿模板
    public static String TRANSMISSION_TEMPLATE = "2";
    
    //定义常量, appId、appKey、masterSecret  在"个推控制台"中获得的应用配置  
    // 由IGetui管理页面生成，是您的应用与SDK通信的标识之一，每个应用都对应一个唯一的AppID  
    private static String appId = "91xHV5XfSi7ZoyswEgCS67";
    //private static String appId = "pPyZWvH3Fa6PXba10aJ009";
    // 预先分配的第三方应用对应的Key，是您的应用与SDK通信的标识之一。  
    private static String appKey = "z8iJmLUhek9a4Du1Papnc1";  
    //private static String appKey = "b7dOGlNPHR7pqwUxDhpTi4";  
    // 个推服务端API鉴权码，用于验证调用方合法性。在调用个推服务端API时需要提供。（请妥善保管，避免通道被盗用）  
    private static String masterSecret = "uAo6zbz6lC6y5uAJjRduX3";
    
    // 设置通知消息模板  
    /* 
     * 1. appId 
     * 2. appKey 
     * 3. 要传送到客户端的 msg 
     * 3.1 标题栏：key = title,  
     * 3.2 通知栏内容： key = titleText, 
     * 3.3 穿透内容：key = transText  
     */  
    private static NotificationTemplate getNotifacationTemplate(String appId, String appKey, Map<String, String> msg){  
        // 在通知栏显示一条含图标、标题等的通知，用户点击后激活您的应用  
        NotificationTemplate template = new NotificationTemplate();  
        // 设置appid，appkey  
        template.setAppId(appId);  
        template.setAppkey(appKey);  
        // 穿透消息设置为，1 强制启动应用  
        template.setTransmissionType(1);  
        // 设置穿透内容  
        System.out.println(msg.get("title") + "::" + msg.get("titleText") + "::" + msg.get("transText"));  
        template.setTransmissionContent(msg.get("transText"));  
        // 设置style  
        Style0 style = new Style0();  
        // 设置通知栏标题和内容  
        style.setTitle(msg.get("title"));  
        style.setText(msg.get("titleText"));  
        // 设置通知，响铃、震动、可清除  
        style.setRing(true);  
        style.setVibrate(true);  
        style.setClearable(true);  
        // 设置  
        template.setStyle(style);  
          
        return template;  
    } 
    
    // 设置透穿通知消息模板  
    /* 
     * 1. appId 
     * 2. appKey 
     * 3. 要传送到客户端的 msg 
     * 3.1 标题栏：key = title,  
     * 3.2 通知栏内容： key = titleText, 
     * 3.3 穿透内容：key = transText  
     */  
    private static TransmissionTemplate getTransmissionTemplate(String appId, String appKey, String msg){  
        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        template.setTransmissionType(2);
        template.setTransmissionContent(msg);
        // 设置定时展示时间
        // template.setDuration("2015-01-16 11:40:00", "2015-01-16 12:24:00");
        return template;
    } 
    
    // 对单个用户推送消息  
    /* 
     * 1. cid 
     * 2. 要传到客户端的 msg 
     * 2.1 标题栏：key = title,  
     * 2.2 通知栏内容： key = titleText, 
     * 2.3 穿透内容：key = transText  
     */  
    public IPushResult pushMsgToSingle(String cid, Map<String, String> msg) {  
        // 代表在个推注册的一个 app，调用该类实例的方法来执行对个推的请求  
        IGtPush push = new IGtPush(appKey, masterSecret);  
        // 创建信息模板  
        NotificationTemplate template = getNotifacationTemplate(appId, appKey, msg);  
        //定义消息推送方式为，单推  
        SingleMessage message = new SingleMessage();  
        // 设置推送消息的内容  
        message.setData(template);  
        // 设置推送目标  
        Target target = new Target();  
        target.setAppId(appId);  
        // 设置cid  
        target.setClientId(cid);  
        // 获得推送结果  
        IPushResult result = push.pushMessageToSingle(message, target);  
        /* 
         * 1. 失败：{result=sign_error} 
         * 2. 成功：{result=ok, taskId=OSS-0212_1b7578259b74972b2bba556bb12a9f9a, status=successed_online} 
         * 3. 异常 
         */  
        return result;  
    }
    
    // 对单个用户推送消息  
    /* 
     * 1. cid 
     * 2. 要传到客户端的 msg 
     * 2.1 标题栏：key = title,  
     * 2.2 通知栏内容： key = titleText, 
     * 2.3 穿透内容：key = transText  
     */  
    public IPushResult pushTransmissionMsgToSingle(String cid, String msg) {  
        // 代表在个推注册的一个 app，调用该类实例的方法来执行对个推的请求  
        IGtPush push = new IGtPush(appKey, masterSecret);  
        // 创建信息模板  
        /*AbstractTemplate template = getNotifacationTemplate(appId, appKey, msg);
        if(NOTIFICATION_TEMPLATE.equals(templateType)) {
            template = getNotifacationTemplate(appId, appKey, msg);
        }else if(TRANSMISSION_TEMPLATE.equals(templateType)) {
            template = getTransmissionTemplate(appId, appKey, msg);
        }*/
        TransmissionTemplate template = getTransmissionTemplate(appId, appKey, msg);
        //定义消息推送方式为，单推  
        SingleMessage message = new SingleMessage();  
        // 设置推送消息的内容  
        message.setData(template);  
        // 设置推送目标  
        Target target = new Target();  
        target.setAppId(appId);  
        // 设置cid  
        target.setClientId(cid);  
        // 获得推送结果  
        IPushResult result = push.pushMessageToSingle(message, target);  
        /* 
         * 1. 失败：{result=sign_error} 
         * 2. 成功：{result=ok, taskId=OSS-0212_1b7578259b74972b2bba556bb12a9f9a, status=successed_online} 
         * 3. 异常 
         */  
        return result;  
    }
    
    // 对多个用户推送消息  
    /* 
     * 1. cids 
     * 2. 要传到客户端的 msg 
     * 2.1 标题栏：key = title,  
     * 2.2 通知栏内容： key = titleText, 
     * 2.3 穿透内容：key = transText  
     */
    public IPushResult pushMsgToList(List<String> cids, Map<String, String> msg) {
        // 代表在个推注册的一个 app，调用该类实例的方法来执行对个推的请求  
        IGtPush push = new IGtPush(appKey, masterSecret); 
        // 创建信息模板  
        NotificationTemplate template = getNotifacationTemplate(appId, appKey, msg);  
        //定义消息推送方式为群组推送
        ListMessage message = new ListMessage();
        message.setData(template);
        // 设置消息离线，并设置离线时间
        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 1000 * 3600);
        //声明需要推送的群体Targets
        List<Target> targets = new ArrayList<Target>();
        for (String cid : cids) {
            if(StringUtils.isNotBlank(cid)){
                Target target = new Target();
                target.setAppId(appId);
                target.setClientId(cid);
                targets.add(target);
            }
        }
        
        // taskId用于在推送时去查找对应的message
        String taskId = push.getContentId(message);
        //获取推送结果
        IPushResult ret = push.pushMessageToList(taskId, targets);
        return ret;
    }
    
    
    
    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        AppPushUtils app = new AppPushUtils();
        String cid = "034d05445fe877c7426e7b5b0acf38ef";
        String cid1 = "2ea4618246d2ee3ede5605ce01cc088d";
        String cid2 = "0d9dd24a8bbede4fd214de90746976ae";
        String cid3 = "585d8e19ed3d4ac2b916a571bf66819a";
        Map<String, String> msg = new HashMap<String, String>();
        msg.put("title", "rms alert notice test");
        msg.put("titleText", "rms alert notice content test");
        msg.put("transText", "like to be alone");
        Map<String, String> msg1 = new HashMap<String, String>();
        msg1.put("title", "rms alert notice test");
        msg1.put("content", "rms alert notice content test");
        msg1.put("payload", "like to be alone");
        ObjectMapper json = new ObjectMapper();
        String message = json.writeValueAsString(msg1);
        //IPushResult result1 = app.pushMsgToSingle(cid2, msg, AppPushUtils.TRANSMISSION_TEMPLATE);
        //IPushResult result1 = app.pushTransmissionMsgToSingle(cid1, message );
       // IPushResult result2 = app.pushTransmissionMsgToSingle(cid2, message );
        IPushResult result3 = app.pushTransmissionMsgToSingle(cid3, message );
        //IPushResult result = app.pushMsgToSingle(cid, msg);
        System.out.println(result3.getResponse().toString());
        /*IPushResult result = app.pushMsgToSingle(cid, msg);
        System.out.println(result.getResponse().toString());
        String cid1 = "2ea4618246d2ee3ede5605ce01cc088d";
        IPushResult result1 = app.pushMsgToSingle(cid1, msg);
        System.out.println(result1.getResponse().toString());*/
        /*List<String> cids = new ArrayList<String>();
        cids.add(cid);
        cids.add(cid1);
        IPushResult ret = app.pushMsgToList(cids, msg);
        System.out.println(ret.getResponse().toString());*/
    }
}
